import React, { Component } from 'react'
import { useRef } from 'react'
import ReactDOM from 'react-dom'

// 类式组件
/* class Demo extends Component {
    state = { count: 0 }

    add = () => {
        this.setState(state => ({ count: state.count + 1 }))
    }

    componentDidMount() {
        this.timer = setInterval(() => {
            this.setState(state => ({ count: state.count + 1 }));
            // console.log(1);
        }, 1000);
    }

    componentWillUnmount() {
        clearInterval(this.timer)
    }

    unmount = () => {
        ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }

    show = () => {
        alert(this.myRef.value)
    }

    render() {
        return (
            <div>
                <input type="text" ref={c=> this.myRef = c}/>
                <h2>SUM: {this.state.count}</h2>
                <button onClick={this.add}>click me + 1</button>
                <button onClick={this.unmount}>click me unmount</button>
                <button onClick={this.show}>click me show</button>
            </div>
        )
    }
} */

// 函数式组件
function Demo() {
    // useState() 返回一个数组 储存状态和操作状态的方法 传的参数为初始化
    const [count, setCount] = React.useState(0)

    function add () {
        setCount(count => count + 1)
    }
       
    // useEffect() componentDidMount & componentDidUpdate & componentWillUnmount的结合
    // 数组中代表监测哪个状态改变(componentDidUpdate), 不写全监测, 空数组不监测(componentDidMount)
    React.useEffect(() => {
        let timer = setInterval(() => {
            setCount(count => count + 1)
        }, 1000);
        // 返回的函数相当于componentWillUnmount
        return () => {
            clearInterval(timer)
        }
    }, [])

    // 卸载组件的回调
    function unmount() {
        ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }

    // useRef() 相当于createRef()
    const myRef = React.useRef()

    function show () {
        alert(myRef.current.value)
    }

    return (
        <div>
            <input type="text" ref={myRef} />
            <h2>SUM: {count}</h2>
            <button onClick={add}>click me + 1</button>
            <button onClick={unmount}>click me unmount</button>
            <button onClick={show}>click me show</button>
        </div>
    )
}

export default Demo